#include "loginfunctionality.h"
#include "Modules/TcpNetwork.h"
#include "Modules/loginmodule.h"
#include "utils/TimeOperation.h"

loginFunctionality::loginFunctionality(std::shared_ptr<NetworkInterface> network,
                                       std::shared_ptr<ModuleInterface> module)
    : FunctionalityInterface()
    , m_network(network)
    , m_module(module)
{
    // m_module->initialize();
    m_network->connect("172.21.93.12", 10003);

    //连接信号和槽
    auto tcpNetwork = dynamic_cast<TcpNetwork *>(m_network.get());

    QObject::connect(tcpNetwork, &TcpNetwork::dataArrival, this, &loginFunctionality::onDataArrival);
}

bool loginFunctionality::executeFunction()
{
    auto lm = dynamic_cast<loginModule *>(m_module.get());
    if (!lm->getIsInitalized()) {
        m_module->initialize();
    }

    if (m_network->socketStatus() == QAbstractSocket::UnconnectedState) {
        m_network->connect("172.21.93.12", 10003);
    }

    QByteArray data = m_module->execute();
    if (data.isEmpty()) {
        OPERATION_FAIL("data is empty", "loginFunctionality", __FILE__, __LINE__, "");
        return false;
    }

    m_network->sendData(data);
    return true;
}

void loginFunctionality::setParameters(const QString &phoneNumber, const QString &passwd)
{
    auto lm = dynamic_cast<loginModule *>(m_module.get());
    lm->setPhoneNumberPasswd(phoneNumber, passwd);
}

void loginFunctionality::onDataArrival(qint64 readBytes)
{
    //需要读取数据
    QByteArray data = m_network->readData(readBytes);
    bool ret = m_module->handleReceiveData(data);
    if (ret) {
        // qDebug() << "注册成功"; //需要发送信号说明注册成功
        auto *lm = dynamic_cast<loginModule *>(m_module.get());
        loginResonpseResult response_result = lm->getResponseResult();
        if (response_result.status == RESPONSE_STATUS_OK)
            emit loginSuccessed(response_result.response_result);
        else
            emit loginFailed(response_result.response_result);
    } else {
        qDebug() << "handleReceiveData error!";
    }
}

// bool loginFunctionality::isLoginSuccessful(const QString &data)
// {
//     if (data.indexOf("Failed") == -1) {
//         //等于-1说明没有找到，因此应该返回的是true
//         qDebug() << "Failed";
//         return true;
//     } else
//         return false;
// }
